<?php
namespace App\Http\Controllers\Admin;

use App\Models\CompanyJobs;
use App\Models\CompanyJobsType;
use App\Models\Area;
use App\Http\Requests\CompanyJobsPostRequest;
use Illuminate\Support\Facades\Response;
use App\Models\Company;
use Illuminate\Support\Facades\Log;
use Illuminate\Support\Facades\DB;
use App\Models\Examination;
use Illuminate\Support\Facades\Request;
/**
 *
 * @author Joker
 *        
 */
class CompanyJobsController extends BaseController
{
    
    /**
     * @var gzxz  工作性质字典  
     * 工作性质  0 全职， 1 兼职 ， 2 实习 ，默认0 全职
     */
    protected $gzxz = array();
    
    /**
     * @var salary 薪资 字典
     * 薪资 0:2k以下；1：2k-5K；2：5k-10k; 3:10k-15k; 4:15k-25k; 5:25k-50k; 6:50k以上 默认0
     */
    protected $salary = array();
    
    /**
     * @var degree 学历
     * 0：大专；1本科；2:硕士；3：博士；4其它； 默认0
     */
    protected $degree = array();
    
    /**
     * @var gznx 工作年限
     * 工作年限 0 应届毕业生 1：1年 ； 2：2年 。。。。10：年  ； >10 为10年以上
     */
    protected $gznx = array();
    
    /**
     * @var status 职位状态 0 未审核  1:审核通过 2:审核不通过; 3:关闭
     */
    protected $status = array();
    
    /**
     * 职位类型
     * @var jobsType
     */
    protected $jobsType = array();
    
    /**
     * @see \App\Http\Controllers\Admin\BaseController::__construct()
     */
    public function __construct() {
        parent::__construct();
        $this->gzxz = array(0=>'全职',1=>'兼职',2=>'实习');
        $this->salary = array(0=>'2k以下',1=>'2k-5k',2=>'5k-10k',3=>'10k-15k',4=>'15k-25k',5=>'25k-50k',6=>'50k以上',7=>'面议');
        $this->gznx = array(0=>'应届毕业生',1=>'1年以下',2=>'1-3年',3=>'3-5年',4=>'5-10年',5=>'10年以上',100=>'不限');
        $this->degree = array(0=>'大专',1=>'本科',2=>'硕士',3=>'博士',4=>'其他',100=>'不限');
        $this->status = array(0=>'未审核',1=>'审核通过',2=>'审核不通过',3=>'关闭');
    }
    
    /**
     * 以审核通过的企业职位列表
     */
    public function index(\Illuminate\Http\Request $req)
    {
        if(!$this->user->can('viewCompanyJobs')) abort(405);
        $title = $req->input('title');
        $username = $req->input('username');
        $query = CompanyJobs::whereIn('status',[1,2,3]);
        if($title)
            $query->where('title','like','%'.$title.'%');
        if($username)
        {
            $companyids = Company::where('name','like','%'.$username.'%')->lists('id');
            $query->whereIn('company_id',$companyids);
        }
        $jobs = $query->orderBy('published_at','desc')->orderBy('jobs_id','desc')->paginate(20);
        
        return view('admin.enterprise.jobs.index')->with('jobs',$jobs)
                ->with('title',$title)->with('username',$username);
    }
    
    /**
     * 未审核通过的企业职位列表
     */
    public function notAudit(\Illuminate\Http\Request $req)
    {
        if(!$this->user->can('viewCompanyJobs')) abort(405);
        $title = $req->input('title');
        $username = $req->input('username');
        $query = CompanyJobs::where('status','=',0);
        if($title)
            $query->where('title','like','%'.$title.'%');
        if($username)
        {
            $companyids = Company::where('name','like','%'.$username.'%')->lists('id');
            $query->whereIn('company_id',$companyids);
        }
        $jobs = $query->orderBy('published_at','desc')->orderBy('jobs_id','desc')->paginate(20);
        
        return view('admin.enterprise.jobs.index')->with('jobs',$jobs)
                ->with('title',$title)->with('username',$username);
    }
    
    /**
     * 新增
     */
    public function create()
    {
        if(!$this->user->can('editCompanyJobs')) abort(405);
        
        $parentType = CompanyJobsType::where(array('parent_id'=>0,'display'=>0))->get();
        $parentArea = Area::where('pid','=',0)->get();
        $companys = Company::all();
        $exams = Examination::all();
        return view('admin.enterprise.jobs.details')
            ->with('jobsType',$parentType)
            ->with('areas',$parentArea)
            ->with('companys',$companys)
            ->with('gznx',$this->gznx)
            ->with('degree',$this->degree)
            ->with('examinations',$exams)
            ->with('status',$this->status)
            ->with('gzxz',$this->gzxz)
            ->with('blademode','add');
    }
    
    /**
     * 职位详情
     * @param integer $id
     */
    public function edit($id)
    {
        if(!$this->user->can('viewCompanyJobs')) abort(405);
        
        $jobs = CompanyJobs::find($id);
        if(empty($jobs)) abort(404);
        $exams = Examination::all();
        $thrtype = CompanyJobsType::where(array('parent_id'=>$jobs->category->parent_id,'display'=>0))->get();
        $pid = CompanyJobsType::where(array('cat_id'=>$jobs->category->parent_id,'display'=>0))->pluck('parent_id');
        $subtype = CompanyJobsType::where(array('parent_id'=>$pid,'display'=>0))->get();
        $parentType = CompanyJobsType::where(array('parent_id'=>0,'display'=>0))->get();

        return view('admin.enterprise.jobs.details')
                ->with('result',$jobs)
                ->with('jobsType',$parentType)
                ->with('subtype',$subtype)
                ->with('thrtype',$thrtype)
                ->with('pid',$pid)
                ->with('areas',$this->getAreas($jobs->area))
                ->with('gznx',$this->gznx)
                ->with('degree',$this->degree)
                ->with('examinations',$exams)
                ->with('status',$this->status)
                ->with('gzxz',$this->gzxz)
                ->with('blademode','edit');
    }
    
    /**
     * 保存数据
     * @param CompanyJobsPostRequest $req
     */
    public function store(CompanyJobsPostRequest $req)
    {
        if(!$this->user->can('editCompanyJobs'))
            return $this->formatJson('error',$this->permerror);
        
        $data = $req->only('name','company_id','firstId','parentId','catId','area','salary','degree','gznx','gzxz','intro',
            'description','status','test','examid','jobs_id','recruitment','salary_lower','salary_high');
        $company = Company::find($data['company_id']);
        if(empty($company))
        {
            return $this->formatJson('error','公司信息错误！');
        }
        if(empty($data['firstId']) || empty($data['parentId']) || empty($data['catId']) || $data['firstId'] == 0 || $data['parentId'] == 0 || $data['catId'] == 0)
        {
            return $this->formatJson('error','请选择职位分类');
        }
        if(empty($data['area']) || $data['area'] == 0)
        {
            return $this->formatJson('error','请选工作城市');
        }
        if(!empty($data['jobs_id']) && is_numeric($data['jobs_id']) && $data['jobs_id'] >0)
        {
            $jobEntity = CompanyJobs::find($data['jobs_id']);
            $jobEntity->title       = $data['name'];
            $jobEntity->recruitment = $data['recruitment'];
            $jobEntity->company_id  = $data['company_id'];
            $jobEntity->cat_id      = $data['catId'];
            $jobEntity->area        = $data['area'];
            $jobEntity->salary      = 0;
            $jobEntity->degree      = $data['degree'];
            $jobEntity->gznx        = $data['gznx'];
            $jobEntity->gzxz        = $data['gzxz'];
            $jobEntity->intro       = $data['intro'];
            $jobEntity->description = $data['description'];
            $jobEntity->status      = $data['status'];
            if($jobEntity->status != 1)
            {
                $company->decrementDel('jobs_count',1);
            }
            $jobEntity->test        = $data['test'];
            $jobEntity->exam_id     = $data['examid'];
            $jobEntity->user_id     = $this->user->id;
            $jobEntity->salary_lower= $data['salary_lower'];
            $jobEntity->salary_high = $data['salary_high'];
            try {
                $jobEntity->save();
            }catch (\PDOException $e){
                Log::info(['修改职位信息异常'=>$e->getMessage()]);
                return $this->formatJson('error','职位编辑异常！');
            }
        }
        else
        {
            $insert_row =  array(
                'title'       => $data['name'],
                'recruitment' => $data['recruitment'],
                'company_id'  => $data['company_id'],
                'cat_id'      => $data['catId'],
                'area'        => $data['area'],
                'salary'      => 0,
                'degree'      => $data['degree'],
                'gznx'        => $data['gznx'],
                'gzxz'        => $data['gzxz'],
                'intro'       => $data['intro'],
                'description' => $data['description'],
                'status'      => 1,
                'test'        => $data['test'],
                'exam_id'     => $data['examid'],
                'user_id'     => $this->user->id,
                'salary_lower'=> $data['salary_lower'],
                'salary_high' => $data['salary_high'],
                'published_at'=> date('Y-m-d H:i:s'),
                'validated_at'=> date('Y-m-d H:i:s')
            );
            DB::beginTransaction();
            try{
                $jobEntity = CompanyJobs::firstOrCreate($insert_row);
                $company->incrementAdd('jobs_count',1);
                DB::commit();
            }catch (\PDOException $e){
                Log::info(['职位新增异常'=>$e->getMessage()]);
                DB::rollBack();
                return $this->formatJson('error','职位新增异常');
            }
        }
        
        return Response::json(array('id'=>$jobEntity->jobs_id,'status'=>'success','msg'=>'保存数据成功！','redirectUrl'=>'/admin/enterprise/jobs/index'));
    }



    /**
     * 职位详情页面
     */
    /**
     * @param  $id
     */
    public function show($id)
    {
        if(!$this->user->can('viewCompanyJobs')) return $this->formatJson('false');

        $result = CompanyJobs::where('jobs_id','=',$id)->first();

        if(empty($result))
        {
            return $this->formatJson('false');
        }

        $result->companyname = $result->company->name;
        $result->areaname = $result->cityname ='';
        if(count($result->areas)>0){
            $result->areaname = $result->areas->title;
            $result->cityname = Area::where('area_id','=',$result->areas->pid)->pluck('title').">";
        }
        $result->typename = $result->ptypename ='';
        if(count($result->category)>0){
            $result->typename = $result->category->name;
            $result->ptypename = CompanyJobsType::where(array('cat_id'=>$result->category->parent_id,'display'=>0))->pluck('name').">";
        }
        $gzxz = $this->gzxz;
        $salary = $this->salary;
        $gznx = $this->gznx;
        $degree = $this->degree;
        $result->gzxz_name = $gzxz[$result->gzxz];
        $result->salary_name = $salary[$result->salary];
        $result->gznx_name = $gznx[$result->gznx];
        $result->degree_name = $degree[$result->degree];

        if($result->test == 0){
            $result->test = '不开启';
        }else{
            $result->test ='开启';
        }
        $result->recruitment =$result->recruitment ? :'不限';

        return $this->formatJson('success','获取信息成功',$result);
    }


    /**
     * 企业审核
     */
    public function jobsValidate(\Illuminate\Http\Request $req)
    {
        if(!$this->user->can('editCompanyJobs'))
            return $this->formatJson('error',$this->permerror);

        $data = $req->only('status','jobs_id');
        if(empty($data['status']))
        {
            return $this->formatJson('error','请选择审核结果！');
        }
        $jobs = CompanyJobs::find($data['jobs_id']);
        $jobs->status = $data['status'];
        $jobs->save();
        if($jobs->status == 1)
            return $this->formatJson('success',"职位：［ ".$jobs->title." ］审核通过！",$jobs,'/admin/enterprise/jobs/noverify');
        else if($jobs->status == 2)
            return $this->formatJson('success',"职位：［ ".$jobs->title." ］不通过！",$jobs,'/admin/enterprise/jobs/noverify');
        else if($jobs->status == 3)
            return $this->formatJson('success',"职位：［ ".$jobs->title." ］关闭！",$jobs,'/admin/enterprise/jobs/noverify');
    }



    /**
     * 删除
     */
    public function destroy($id)
    {
        if(!$this->user->can('deleteCompanyJobs')) 
            return $this->formatJson('error',$this->permerror);
        
        $jobs = CompanyJobs::find($id);
        if(empty($jobs))
            return $this->formatJson('error',$this->noResource);
        
        DB::beginTransaction();
        try{
            $jobs->delete();
            $company = Company::find($jobs->company_id);
            $company->decrementDel('jobs_count',1);
            DB::commit();
        }catch (\PDOException $e){
            Log::info(['删除职位异常'=>$e->getMessage()]);
            DB::rollBack();
            return $this->formatJson('error','删除失败');
        }
        return $this->formatJson('success','成功删除［'.$jobs->title.']');
    }
    
    /**
     * 根据企业获取相关考试 
     */
    public function getExams($id)
    {
        if(Request::ajax())
        {
            $exams = Examination::where('company_id','=',$id)->get();
            if(count($exams)>0)
            {
                return $this->formatJson('success','成功！',$exams);
            }
            else 
            {
                return $this->formatJson('error','没有相关试卷，请先组卷。');
            }
        }
    }
    
    /**
     * 根据地区编号获取父地区
     */
    protected function getAreas($area_id)
    {
        $nowArea = Area::find($area_id);
        $html = '';
        $sameLevel = Area::where('pid','=',$nowArea->pid)->get();
        if($nowArea->pid > 0)
        {
            $parentArea = $nowArea->parentArea;
            $parentSameLevel = Area::where('pid','=',$parentArea->pid)->get();
            $html .= '<select name="parentArea" class="form-control" onchange="childAreas(this.value,\'areas\',\'city\')">';
            foreach ($parentSameLevel as $psl)
            {
                if($psl->area_id === $parentArea->area_id)
                {
                    $html.='<option value="'.$psl->area_id.'" selected>'.$psl->title.'</option>';
                }
                else
                {
                    $html.='<option value="'.$psl->area_id.'">'.$psl->title.'</option>';
                }
            }
            $html.='</select>';
        }
        $html.="\n";
        $html.='<select name="area" class="form-control" id="city">';
        foreach ($sameLevel as $sl)
        {
            if($sl->area_id === $area_id)
            {
                $html.='<option value="'.$sl->area_id.'" selected>'.$sl->title.'</option>';
            }
            else
            {
                $html.='<option value="'.$sl->area_id.'">'.$sl->title.'</option>';
            }
        }
        $html.='</select>';
        return $html;
    }
    
    /**
     * 根据子分类获取父分类 以及子分类同级所有分类和父分类同级分类
     */
    protected function getJobsTypes($cat_id)
    {
        $nowCate = CompanyJobsType::find($cat_id);
        $html='';
        $sameLevel = CompanyJobsType::where(array('parent_id'=>$nowCate->parent_id,'display'=>0))->orderBy('sort','ASC')->orderBy('created_at','ASC')->get();
        if($nowCate->parent_id >0 )
        {
            $parentCate = $nowCate->parentCate;
            if($parentCate->parent_id > 0)
            {
                $where = array('parent_id'=>0,'display'=>0);
                $parentSameLevel = CompanyJobsType::where($where)->orderBy('sort','ASC')->orderBy('created_at','ASC')->get();
                $html .= '<select name="firstId" class="form-control" onchange="jobstype(this.value,\'companyjobtype\',\'parentId\')">';
                foreach ($parentSameLevel as $psl)
                {
                    if($psl->cat_id === $parentCate->cat_id)
                    {
                        $html.='<option value="'.$psl->cat_id.'" selected>'.$psl->name.'</option>';
                    }
                    else
                    {
                        $html.='<option value="'.$psl->cat_id.'">'.$psl->name.'</option>';
                    }
                }
                $html.='</select>';
            }
            $html.="\n";
            $where = array('parent_id'=>$parentCate->parent_id,'display'=>0);
            $parentSameLevel = CompanyJobsType::where($where)->orderBy('sort','ASC')->orderBy('created_at','ASC')->get();
            $html .= '<select name="parentId" class="form-control" onchange="jobstype(this.value,\'companyjobtype\',\'catId\')">';
            foreach ($parentSameLevel as $psl)
            {
                if($psl->cat_id === $parentCate->cat_id)
                {
                    $html.='<option value="'.$psl->cat_id.'" selected>'.$psl->name.'</option>';
                }
                else 
                {
                   $html.='<option value="'.$psl->cat_id.'">'.$psl->name.'</option>';
                }
            }
            $html.='</select>';
        }
        $html.="\n";
        $html.='<select name="catId" class="form-control" id="catId">';
        foreach ($sameLevel as $sl)
        {
            if($sl->cat_id === $cat_id)
            {
                $html.='<option value="'.$sl->cat_id.'" selected>'.$sl->name.'</option>';
            }
            else
            {
                $html.='<option value="'.$sl->cat_id.'">'.$sl->name.'</option>';
            }
        }
        $html.='</select>';
        return $html;
    }
}